package com.Qinmeiwei.web.util.tag;

import com.Qinmeiwei.web.util.Constants;


public class JsTag extends ResourceTag {

	/** 是否使用非阻塞式加载JS */
	protected boolean nonBlocking = false;

	/** The Constant SCRIPT_BEGIN. */
	protected static final String SCRIPT_BEGIN = "<script type='text/javascript'>\n";

	/** The Constant CREATE_SCRIPT_FUNCTION. */
	protected static final String CREATE_SCRIPT_FUNCTION = "createScript";

	/** The Constant SCRIPT_END. */
	protected static final String SCRIPT_END = "</script>\n";

	/** DEBUG模式后缀. */
	protected static final String JS_DEBUG_POSTFIX = ".js";

	/** 压缩后缀. */
	protected static final String JS_POSTFIX = ".min.js";

	/** 非阻塞式加载JS脚本. */
	protected static final String SCRIPT = 
			" var dynamic_script_head=document.getElementsByTagName('head')[0];\n" + 
			"function " + CREATE_SCRIPT_FUNCTION + "(js_name){" + "var js=document.createElement('script');" + 
			"js.type='text/javascript';js.src=js_name;" + "dynamic_script_head.appendChild(js);}\n";

	protected String create() {
		if (nonBlocking) {
			StringBuilder source = new StringBuilder(SCRIPT_BEGIN);
			if (!isImported(CREATE_SCRIPT_FUNCTION))
				source.append(SCRIPT);
			for (String s : pageResourceSet) {
				source.append(CREATE_SCRIPT_FUNCTION).append("('");
				buildPath(source, s);
				source.append("');\n");
			}
			source.append(SCRIPT_END);
			return source.toString();
		} else {
			StringBuilder source = new StringBuilder();
			for (String s : pageResourceSet) {
				source.append("<script type='text/javascript' src='");
				buildPath(source, s);
				source.append("'>").append(SCRIPT_END);
			}
			return source.toString();
		}

	}

	protected void buildPath(StringBuilder source,String jsName){
		if(jsName.startsWith("http")){
			source.append(jsName);
			return;
		}
		source.append(Constants.JS)
			  .append("/")
		  	  .append(jsName);
		  	  if(isDebug()){
		  		  source.append(JS_DEBUG_POSTFIX);
		  	  }else{
		  		if(jsName.endsWith(".min")){
		  			source.append(JS_DEBUG_POSTFIX);
		  		  }else{
		  			source.append(JS_POSTFIX);
		  		  }
		  	  }
	}

	public boolean isNonBlocking() {
		return nonBlocking;
	}

	public void setNonBlocking(boolean nonBlocking) {
		this.nonBlocking = nonBlocking;
	}
}
